#-*- coding: utf-8 -*-
'''
    Author: hkk
'''
import time
from django.contrib.auth.decorators import login_required
from django.db.models import Count
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.core.urlresolvers import reverse
from commons.paginator import paginator
from django.shortcuts import render_to_response, HttpResponseRedirect, HttpResponse, render
from vmware.forms import ContentForm,ContentFormApply,ContentFormEdit
from django.contrib.auth.decorators import permission_required, login_required
from vmware.models import vmware_content,vmware_resource
from controller.public.permissions import check_perms
import json,time,collections


@login_required()
#@permission_required('view_vm', raise_exception=True)
def vmware_list(request):
     if check_perms(request, 'vmware.view_vm', raise_exception=True):
       user = request.user.id
       if user != 1:
           content = vmware_content.objects.filter(created_by_id=user).order_by('vm_status')
           data = paginator(request, content)
       else:
           content = vmware_content.objects.order_by('vm_status')
           data = paginator(request, content)
           data['user']=int(user)
       request.breadcrumbs((('首页', '/'),('申请列表',reverse('vmlist'))))
       return render_to_response('vmware/vmware.html',data)
     else:
        error = u'您没有权限操作@^@，请联系管理员！'
     return render(request, 'error.html', {'request': request, 'error': error})

@login_required
#@permission_required('add_vm', raise_exception=True)
def vmware_apply(request):
    user = request.user
    # 新增资源申请
    error = ""
    if check_perms(request, 'vmware.add_vm', raise_exception=True):
        if request.method == "POST":
            ower=request.POST.get('vm_ower')
            if str(user) == ower:
            # return HttpResponse(str(user))
                form = ContentFormApply(request.POST)
                if form.is_valid():
                    tmp = form.save(commit=False)
                    tmp.created_by_id = request.user.id
                    tmp.save()
                    return HttpResponseRedirect(reverse('vmlist'))
            else:
                error='您的申请人名称有误，请检查'
                return render(request, 'error.html', {'request': request, 'error': error})
        else:
            form = ContentFormApply()
        return render(request, 'vmware/vmware_apply.html', {'request': request, 'form': form, 'error': error})
    else:
        error = u'您没有权限操作@^@，请联系管理员！'
    return render(request, 'error.html', {'request': request, 'error': error})

@login_required
#@permission_required('edit_vm', raise_exception=True)
def vmware_edit(request):
    error = ""
    if check_perms(request, 'vmware.edit_vm', raise_exception=True):
        id = request.GET.get("id")
        if id:
            try:

                content = vmware_content.objects.get(id=id)
                form = ContentFormEdit(instance=content)
                id = id
            except:
                error = "该报告不存在"
                form = ""

        if request.method == "POST":
            content = vmware_content.objects.get(id=id)
            form = ContentFormEdit(request.POST,instance=content)
            # return HttpResponse(form.errors)
            if form.is_valid():
                tmp = form.save(commit=False)
                tmp.created_by_id = request.user.id
                tmp.save()
                return HttpResponseRedirect(reverse('vmlist'))
        return render(request, 'vmware/vmware_edit.html', {'request': request, 'form': form, 'error': error,'id':id})
    else:
        error = u'您没有权限操作@^@，请联系管理员！'
    return render(request, 'error.html', {'request': request, 'error': error})

@login_required
#@permission_required('del_vm', raise_exception=True)
def vmware_recovery(request):
    # 回收虚拟机
    error=''
    response = HttpResponse()
    if check_perms(request, 'vmware.del_vm', raise_exception=True):

        data = json.loads(request.POST.get('data', ''))
        id = int(data['id'])
        cpu=data['cpu']
        mem=data['mem']
        disk=data['disk']
        content = vmware_content.objects.get(id=id)
        #资源池更新
        resource=vmware_resource.objects.get(id=content.vm_cluster_id)
        vmware_resource.objects.filter(id=content.vm_cluster_id).update(vm_leftcpu=int(resource.vm_leftcpu)+int(cpu.split('核')[0]))
        vmware_resource.objects.filter(id=content.vm_cluster_id).update(vm_leftmem=int(resource.vm_leftmem)+int(mem.split('G')[0]))
        vmware_resource.objects.filter(id=content.vm_cluster_id).update(vm_leftdisk=int(resource.vm_leftdisk)+int(disk.split('G')[0]))
        #hosts数量减1
        vmware_resource.objects.filter(id=content.vm_cluster_id).update(vm_hosts=int(resource.vm_hosts)-1)
        vmware_content.objects.get(pk=id).delete()


        response.write(json.dumps(u'成功'))
    else:
        response.write(json.dumps(u'您没有权限操作@^@，请联系管理员！'))


    return response


def vmware_delete(request):
    # 删除申请或者虚拟机
    error=''
    response = HttpResponse()

    data = json.loads(request.POST.get('data', ''))
    id = int(data['id'])
    content = vmware_content.objects.get(id=id)
    # resource=vmware_resource.objects.get(id=content.vm_cluster_id)
    # #hosts数量减1
    # vmware_resource.objects.filter(id=content.vm_cluster_id).update(vm_hosts=int(resource.vm_hosts)-1)
    vmware_content.objects.get(pk=id).delete()
    response.write(json.dumps(u'成功'))


    return response

@login_required
#@permission_required('edit_vm', raise_exception=True)
def vmware_manage(request):

    error = ""
    if check_perms(request, 'vmware.edit_vm', raise_exception=True):
        id = request.GET.get("id")
        if id:
            try:
                content = vmware_content.objects.get(id=id)
                form = ContentForm(instance=content)
                id = id
            except:
                error = "该虚拟机不存在"
                form = ""

        if request.method == "POST":
            content = vmware_content.objects.get(id=id)
            form = ContentForm(request.POST,instance=content)
            owern=request.POST.get('vm_ower')
            vm_id=request.POST.get('vm_cluster')
            status=request.POST.get('vm_status')
            disk=request.POST.get('vm_disk')
            cpu=request.POST.get('vm_cpu')
            mem=request.POST.get('vm_mem')




            #检查ip和主机名是否冲突
            # ip=request.POST.get('vm_ip')
            # hostname=request.POST.get('vm_hostname')
            # iph=vmware_content.objects.filter(vm_ip=ip)
            # hostnameh=vmware_content.objects.filter(vm_hostname=hostname)
            # if form.is_valid():
            #     tmp = form.save(commit=False)
            #     # tmp.created_by_id = created_id
            #     tmp.save()
            #return HttpResponse(int(disk.split("G")[0]))
            if status == "1":

                # if iph :
                #    error = u"该ip已分配,请检查"
                #    return render(request, 'error.html', {'request': request, 'error': error})
                # else:

                    cpulist={0:2,1:4,2:8,3:16,4:32}
                    memlist={0:2,1:4,2:8,3:16,4:32}

                    resource=vmware_resource.objects.get(id=vm_id)
                    # return HttpResponse(resource.vm_sumcpu)
                    vmware_resource.objects.filter(id=vm_id).update(vm_leftcpu=int(resource.vm_leftcpu)-cpulist[int(cpu)])
                    vmware_resource.objects.filter(id=vm_id).update(vm_leftmem=int(resource.vm_leftmem)-memlist[int(mem)])
                    vmware_resource.objects.filter(id=vm_id).update(vm_leftdisk=int(resource.vm_leftdisk)-int(disk.split('G')[0]))
                    #hosts数量加1
                    vmware_resource.objects.filter(id=vm_id).update(vm_hosts=int(resource.vm_hosts)+1)

            if form.is_valid():
                tmp = form.save(commit=False)
                # tmp.created_by_id = created_id
                tmp.save()

            return HttpResponseRedirect(reverse('vmlist'))



        return render(request, 'vmware/vmware_manage.html', {'request': request, 'form': form, 'error': error,'id':id})
    else:
        error = u'您没有权限操作@^@，请联系管理员！'
    return render(request, 'error.html', {'request': request, 'error': error})



def  vmware_cluster(request):

    data = {}
    cluster = vmware_resource.objects.annotate(average_server=Count('vm_cluster')).order_by('id')
    data = paginator(request, cluster)
    request.breadcrumbs((('首页', '/'), ('集群列表', reverse('vmcluster'))))
    if request.method != "POST":
        return render_to_response('vmware/vmware_cluster.html', data)
    else:
        return render_to_response('vmware/vmware_cluster.html', data)




def vmware_cluster_detail(request,id):

    return HttpResponse(id)

@login_required
def cluster_add(request):
    # 新增虚拟化集群
    response = HttpResponse()

    if check_perms(request, 'vmware.add_vmcluster', raise_exception=True):
        error = ""
        if request.method == "POST":
            user = request.user
            data = json.loads(request.POST.get('data', ''))

            clusterName = data['cluster_name']
            cluster = vmware_resource.objects.filter(vm_cluster=clusterName)

            if cluster:
                response.write(json.dumps(u'尼玛，重复了！'))
            elif len(clusterName) == 0:
                response.write(json.dumps(u'你闲的蛋疼么？字都懒得打！'))
            else:
                try:
                    cluster = vmware_resource()
                    cluster.vm_cluster = clusterName
                    cluster.vm_sumcpu = data['cpu']
                    cluster.vm_summem = data['mem']
                    cluster.vm_sumdisk = data['disk']
                    cluster.save()
                except:
                    response.write(json.dumps(u'异常'))
                else:
                    response.write(json.dumps(u'成功'))

        else:
            pass
    else:
        response.write(json.dumps(u'您没有权限操作@^@，请联系管理员！'))

    return response


@login_required
#@permission_required('cmdb.change_idc', raise_exception=True)
def cluster_edit(request):
    # 编辑cluster

    response = HttpResponse()

    if check_perms(request, 'vmware.edit_vmcluster', raise_exception=True):
        data = json.loads(request.POST.get('data', ''))

        id = data['id']

        cluster = vmware_resource.objects.get(pk=id)
        cluster.vm_cluster = data['cluster_name']
        cluster.vm_sumcpu = data['cpu']
        cluster.vm_summem = data['mem']
        cluster.vm_sumdisk = data['disk']

        try:
            cluster.save()
        except:
            response.write(json.dumps(u'失败'))
        else:
            response.write(json.dumps(u'成功'))
    else:
        response.write(json.dumps(u'您没有权限操作@^@，请联系管理员！'))

    return response

@login_required

def cluster_del(request):
    # 删除cluster
    response = HttpResponse()

    if  check_perms(request, 'vmware.del_vmcluster', raise_exception=True):
        data = json.loads(request.POST.get('data', ''))

        id = int(data['id'])
        vmware_resource.objects.get(pk=id).delete()

        response.write(json.dumps(u'成功'))
    else:
        response.write(json.dumps(u'您没有权限操作@^@，请联系管理员！'))

    return response








